<?php

namespace App\Listeners;

use App\Constant\QueueKey;
use App\Events\RiskResultEvent;
use App\Facades\SamLogFacade;
use App\Models\User;
use App\Models\UserApplyRiskLog;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class RiskResultEventListener implements ShouldQueue
{
    use InteractsWithQueue;

    public $queue = QueueKey::QUEUE_RISK_RESULT;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Description:
     * Author: Sam
     * DateTime: 2019-01-29 11:23
     * @param RiskResultEvent $event
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(RiskResultEvent $event)
    {

        /**
         * @var $risk UserApplyRiskLog
         */
        $risk = $event->risk;
        SamLogFacade::debug("风控模型：".json_encode($risk,JSON_UNESCAPED_UNICODE));
        $loan = UserLoanRequest::find($risk->loan_request_id);
        if($risk->status==UserApplyRiskLog::STATUS_SUCCESS){
            //先记录下风控数据
            $loan->risk_status = $risk->status;
            $loan->actually_loan_money = $risk->limit*100;
            $loan->save();
            //用户信息同步
            $user = User::find($loan->user_id);
            if(empty($user->nfsp_user_id)){
                $user_id = $user->id;
                $bank_card_id = $loan->cash_card_choice_id;
                $user_info_id = $loan->user_base_info_id;
                $amount = $risk->limit;
                SamLogFacade::debug("用户【{$user_id}】进行用户信息同步");
                User::userSync($user_id,$bank_card_id,$user_info_id,$amount);
            }
        }elseif($risk->status==UserApplyRiskLog::STATUS_PROCESSING){
            return true;
        }
        elseif($risk->status==UserApplyRiskLog::STATUS_FAILED){
            $loan->risk_status = $risk->status;
            $loan->status = UserLoanRequest::STATUS_RISK_REJECT;
            $loan->failed_time = Carbon::now();
            $loan->save();
        }else{
            $loan->risk_status = $risk->status;
            $loan->status = UserLoanRequest::STATUS_RISK_FAILED;
            $loan->failed_time = Carbon::now();
            $loan->save();
        }
        SamLogFacade::debug("授信【{$loan->id}】风控结果处理成功");
    }
}
